import { RequestWith } from "f2e-server";
import * as fs from 'fs'
import * as path from 'path'
import { ADBFactory, execSafe } from "./utils";

const temp_dir = path.join(__dirname, '../temp')
if (!fs.existsSync(temp_dir)) {
    fs.mkdirSync(temp_dir)
}

export default (adb_factory: ADBFactory) => {

    return {
        install_from_file: async (req: RequestWith<{id: string}>) => {
            const { rawBody } = req
            const tempfile = path.join(temp_dir, Date.now() + '.apk')
            rawBody && fs.writeFileSync(tempfile, rawBody)
            const info = await adb_factory.installApk(req.data.id + '', tempfile)
            fs.unlinkSync(tempfile)
            return {
                success: !!info
            }
        },
        install_from_url: async (req: RequestWith<{id: string, url: string}>) => {
            const { id, url } = req.body || req.data
            const filename = Date.now() + '.apk'
            const tempfile = path.join(temp_dir, filename)
            // 5分钟下载时间
            await execSafe(`cd ${temp_dir} && wget -o log -O ${filename} ${url}`, 300 * 1000)
            // 1分钟安装时间
            const info = await adb_factory.installApk(id + '', tempfile)
            fs.unlinkSync(tempfile)
            return {
                success: !!info
            }
        },
        open_app: async (req: RequestWith<{id: string, pkg: string}>) => {
            const { id, pkg } = req.body || req.data
            const info = await adb_factory.shell(id + '', `monkey -p ${pkg} -v 1`)
            return {
                success: !!info
            }
        },
        list_packages: async (req: RequestWith<{id: string}>) => {
            const { id } = req.body || req.data
            const info = await adb_factory.shell(id + '', `pm list packages`)
            return (info.match(/[^\r\n]+/g) || []).map(line => line.split(':').pop())
        },
    }
}